﻿using AutoMapper;
using MediatR;
using SlaughterItem.Common.Domains.Manages;
using SlaughterItem.Common.Dtos;
using SlaughterItem.Common.Infrastructures.Interfaces;
using SlaughterItem.Enum;

namespace SlaughterItem.API.Application.Commands.Week01.SectionCommands
{
    public class SectionAddHandler : IRequestHandler<SectionAddCommend, Result>
    {
        public IBaseRepository<Sections> sections;
        public IMapper mapper;
        public SectionAddHandler(IBaseRepository<Sections> sections, IMapper mapper)
        {
            this.sections = sections;
            this.mapper = mapper;
        }

        public async Task<Result> Handle(SectionAddCommend request, CancellationToken cancellationToken)
        {
            //定义返回值
            var result=new Result() {Code=(int)CommonErrorCode.Added};
            //此变量获取数据库中是否有此部门
            var AddNum =  sections.GetAll().Where(x => x.SectionId == request.SectionId).Count();
            if (AddNum > 0)
            {
                result.Code = (int)CommonErrorCode.Added;
                return result;
            }
            else
            { 
                //AutoMapper类型转换
                var data=mapper.Map<Sections>(request);
                var AddSectionNum = sections.Add(data);
                if (AddSectionNum > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    return result;
                }
                else
                {
                    result.Code = (int)CommonErrorCode.Added;
                    return result;
                }
            }
        }
    }
}
